//
//  RBVerifyCodeController.m
//  MaterialXBUser
//
//  Created by XBWH on 2024/3/6.
//

#import "RBVerifyCodeController.h"
#import "RBVertificationCodeInputView.h"
#import "RBGenerateUserSigIn.h"

@interface RBVerifyCodeController ()
@property(strong,nonatomic)UIButton *rbBackButton;
@property(strong,nonatomic)UILabel *rbNameLabel;
@property(strong,nonatomic)UILabel *rbInfoLabel;
@property(strong,nonatomic)RBVertificationCodeInputView *codeInputView;
@property(strong,nonatomic)UIButton *rbCodeButton;
@end

@implementation RBVerifyCodeController{
    NSString *_code;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self rb_initViewUI];
    self.rbCodeButton.enabled = NO;
    self.rbCodeButton.backgroundColor = RBColor(217, 217, 217);
    [self rb_codeTimerWithTiming:@selector(CodeTiming:) finish:@selector(CodeFinish)];
    self.rbInfoLabel.text = [NSString stringWithFormat:@"已发送验证码至 %@",self.phoneStr];
}
-(void)rb_initViewUI{
    self.rbBackButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rbBackButton setImage:[UIImage imageNamed:@"blackback"] forState:UIControlStateNormal];
    [self.rbBackButton addTarget:self action:@selector(backButtonTap) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.rbBackButton];
    
    self.rbNameLabel = [UILabel rb_labelWithTitle:@"输入验证码" color:RBColor(51, 51, 51) font:RBPingFangBlodFont(24) alignment:NSTextAlignmentLeft];
    [self.view addSubview:self.rbNameLabel];
    
    self.rbInfoLabel = [UILabel rb_labelWithTitle:@"已发送验证码至" color:RBColor(153, 153, 153) font:RBPingFangFont(12) alignment:NSTextAlignmentLeft];
    [self.view addSubview:self.rbInfoLabel];
    
    self.rbCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rbCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.rbCodeButton addTarget:self action:@selector(codeButtonTap) forControlEvents:UIControlEventTouchUpInside];
    self.rbCodeButton.titleLabel.font = RBPingFangFont(16);
    [self.rbCodeButton setTitleColor:RBColor(255, 255, 255) forState:UIControlStateNormal];
    self.rbCodeButton.backgroundColor = RBColor(217, 217, 217);
    [self.view addSubview:self.rbCodeButton];
    
    CGFloat x = 30;
    CGFloat y = RBScaleWidth(211) + RBSTATUS_BAR_HEIGHT;
    RBVertificationCodeInputView *codeInputView = [[RBVertificationCodeInputView alloc] initWithFrame:CGRectMake(x, y, RBScreenWidth - x * 2, 55)];
    codeInputView.secureTextEntry = NO;
    codeInputView.numberOfVertificationCode = 6;
    [self.view addSubview:codeInputView];
    [codeInputView addObserver:self forKeyPath:@"vertificationCode" options:NSKeyValueObservingOptionNew context:nil];
    self.codeInputView = codeInputView;
    [self.codeInputView becomeFirstResponder];
    
    [self.rbBackButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(RBScaleWidth(10));
        make.top.mas_equalTo(RBSTATUS_BAR_HEIGHT+RBScaleWidth(10));
        make.width.height.mas_equalTo(RBScaleWidth(20));
    }];
    [self.rbNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.rbBackButton.mas_bottom).mas_offset(RBScaleWidth(25));
        make.left.mas_equalTo(RBScaleWidth(20));
    }];
    [self.rbInfoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.rbNameLabel.mas_bottom).mas_offset(RBScaleWidth(10));
        make.left.mas_equalTo(self.rbNameLabel.mas_left);
    }];
    [self.rbCodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(RBScaleWidth(335));
        make.centerX.mas_equalTo(0);
        make.height.mas_equalTo(RBScaleWidth(48));
        make.top.mas_equalTo(RBSTATUS_BAR_HEIGHT + RBScaleWidth(335));
    }];
    self.rbCodeButton.layer.cornerRadius = RBScaleWidth(24);
    self.rbCodeButton.layer.masksToBounds = YES;
    
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"vertificationCode"] && object == self.codeInputView) {
        _code = self.codeInputView.vertificationCode;
        if (_code.length == 6) {
            //网络请求
            [self loadRBSmsLoginURLData:_code];
        }
    }
}
-(void)loadRBSmsLoginURLData:(NSString *)code{
    if ([RBTool rb_isEmptyStr:self.phoneStr]) {
        [MBProgressHUD rb_showAutoMessage:@"请输入正确的手机号" ToView:RBWindow];
        return;
    }
    if ([RBTool rb_isEmptyStr:code]) {
        [MBProgressHUD rb_showAutoMessage:@"请输入验证码" ToView:RBWindow];
        return;
    }
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"username"] = self.phoneStr;
    dict[@"term"] = @"user";
    dict[@"smscode"] = code;
    MJWeakSelf
    [RBNetworkTool POST:RBSmsLoginURL parameters:dict success:^(id responseObject) {

        if ([responseObject[@"success"] boolValue]) {
            NSString *token = [NSString stringWithFormat:@"%@",responseObject[@"result"][@"token"]];
            RBUserModel *userModel = [RBUserModel mj_objectWithKeyValues:responseObject[@"result"][@"userInfo"]];
            userModel.token = token;
            if (userModel.imSecret.length==0) {
                userModel.imSecret = secretkey;
            }
            if (userModel.imAppId.length==0) {
                userModel.imAppId = [NSString stringWithFormat:@"%d",sdkappid];
            }
            
            //保存用户信息
            [RBArchiveTool rb_saveUserModel:userModel];

            [[RBLogInAndOutTool shareInstance] rb_saveLogin:userModel.userId withAppId:SDKAPPID withUserSig:[RBGenerateUserSigIn genTestUserSig:userModel.userId]];
            
            // 通知更新个人信息
            [[NSNotificationCenter defaultCenter] postNotificationName:@"RBUpDateUserInfmation" object:nil];
            // 登录成功通知刷新数据
            [[NSNotificationCenter defaultCenter] postNotificationName:@"RBUpDateRefershData" object:nil];
        
            NSString *selectIndex = [NSString stringWithFormat:@"%ld",self.selectedIndex];
            NSDictionary *dict = @{
                                    @"logSelect":selectIndex,
                                    @"source":self.source?self.source:@""
                                   };
            [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"RBLoginSuccess" object:nil userInfo:dict]];
            
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        }
    } error:^(id responseObject) {
    } failure:^(NSError *error) {
    }];
}
#pragma mark - 响应事件
-(void)backButtonTap{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)codeButtonTap{
    
}
- (void)rb_codeTimerWithTiming:(SEL)timingMethod finish:(SEL)finishMethod{
    MJWeakSelf;
    __block int timeout=60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0)
        {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                weakSelf.rbCodeButton.enabled = YES;
                weakSelf.rbCodeButton.backgroundColor = RBColor(242, 48, 48);
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
                [weakSelf performSelector:finishMethod withObject:nil];
                
            });
        }else{
            //在主线程设置按钮不可用
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.rbCodeButton.enabled = NO;
                weakSelf.rbCodeButton.backgroundColor = RBColor(217, 217, 217);
            });
            
            // int minutes = timeout / 60;
            int seconds = timeout % 60;
            if (seconds == 0) {
                seconds = timeout;
            }
            NSString *strTime = [NSString stringWithFormat:@"%.2d秒后可重新获取", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [weakSelf performSelector:timingMethod withObject:strTime];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

- (void)CodeTiming:(NSString *)timeStr{
    self.rbCodeButton.titleLabel.text = timeStr;
    [self.rbCodeButton setTitle:timeStr forState:UIControlStateNormal];
    self.rbCodeButton.userInteractionEnabled = NO;
}

- (void)CodeFinish{
    self.rbCodeButton.titleLabel.text = @"获取验证码";
    [self.rbCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    self.rbCodeButton.userInteractionEnabled = YES;
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
